package com.cc.blog.admin.service.impl;

import com.cc.blog.admin.domain.dto.UpdateAdminUserPasswordReqDTO;
import com.cc.blog.admin.domain.vo.FindUserInfoRspVO;
import com.cc.blog.admin.mapper.UserMapper;
import com.cc.blog.admin.service.AdminUserService;
import com.cc.blog.common.enums.CodeEnum;
import com.cc.blog.common.utils.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author cc
 * @Date 2024/07/10 14:54
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Result updatePassword(UpdateAdminUserPasswordReqDTO dto) {
        // 拿到用户名、密码
        String username = dto.getUsername();
        String password = dto.getPassword();
        // 加密密码
        String encodePassword = passwordEncoder.encode(password);
        // 更新到数据库
        int count = userMapper.updatePasswordByUsername(username, encodePassword);

        return count == 1 ? Result.success() : Result.fail(CodeEnum.USERNAME_NOT_FOUND);
    }

    @Override
    public Result findUserInfo() {
        // 获取存储在 ThreadLocal 中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 拿到用户名
        String username = authentication.getName();

        return Result.success(FindUserInfoRspVO.builder().username(username).build());
    }
}